$(function(){
	//验证码
	$("#randImgId, .changtxt").click(function(){
		changeRand();
	});
	//回车事件
	$("#login_form input").bind("keydown",function(event){
		switch (event.keyCode){
		case 13://enter
			login();
			break;
		}
	});
	//ajaxform提交表单
	var options = {
		url : ctx + "/dologin",
		dataType : 'json',
		type : "post",
		success : function(ret) {
			if(ret.code==1){//登录失败
				$.my.info(ret.message);
				$("#randId").val("");
				changeRand();
			}else{//登录成功 
				var url = tempUrl;
				if(url){
					location.href= url;
					return;
				}
				top.location.href= ctx + "/info";
			}
		}
	};
	$("#login_form").ajaxForm(options);
	//提交表单按钮
	$(".loginBtn").click(function(){
		login();
	});
	$("#usernameId").blur(function(){
		if(!checkUsername()){
			return false;
		}
		/**
		$.ajax( {
			url : ctx+"/checkUsernameLogin?username="+$("#usernameId").val(),
			cache : false,
			//async : false,
			type: "POST",
			success : function(data) {
				if(data.code == 0){ //成功
					showTip($("#cellphoneId"),1,"");
				}else{//失败
					$("#usernameId").attr("checkStatus","1");
					showTip($("#usernameId"),2,data.message);
				}
			},
			error : function() {
				$.my.error("系统错误,请联系管理员");
			}
		});*/
		showTip($(this),1,"");
		return true;
	});
	$("#passwdId").blur(function(){
		if(!checkPasswd()){
			return false;
		}
		showTip($(this),1,"");
		return true;
	});
	$("#randId").blur(function(){
		if(!checkRand()){
			return false;
		}
		$.ajax( {
			url : ctx+"/checkRand?rand="+$("#randId").val(),
			cache : false,
			type: "POST",
			success : function(data) {
				if(data.code == 0){ //成功
					showTip($("#randId"),1,"");
				}else{//失败
					$("#randId").attr("checkStatus","1");
					showTip($("#randId"),2,data.message);
				}
			},
			error : function() {
				$.my.error("系统错误,请联系管理员");
			}
		});
		showTip($(this),1,"");
		return true;
	});
});

function checkUsername(){
	var $this = $("#usernameId");
	if($this.attr("checkStatus") == "1"){
		showTip($this,2,"请输入有效的用户名");
		//$this.focus().select();
		return false;
	}
	var v = $.trim($this.val());
	if(v.length == 0 || (!v.isMobile() && !v.isEmail())){
		showTip($this,2,"请输入有效的用户名");
		//$this.focus().select();
		return false;
	}
	return true;
}
function checkPasswd(){
	var $this = $("#passwdId");
	var v = $.trim($this.val());
	if(v.length == 0 || !v.isPassword()){
		showTip($this,2,"请输入有效密码");
		//$this.focus().select();
		return false;
	}
	return true;
}
function checkRand(){
	var $this = $("#randId");
	if($this.attr("checkStatus") == "1"){
		showTip($this,2,"请输入有效验证码");
		//$this.focus().select();
		return false;
	}
	var v = $.trim($this.val());
	if(v.length != 5 ){
		showTip($this,2,"请输入有效验证码");
		//$this.focus().select();
		return false;
	}
	return true;
}

function login(){
	if(!checkUsername() 
			|| !checkPasswd() 
			|| !checkRand() ){
		return false;
	} 
	$("#login_form").submit();
}

function changeRand(){
	$("#randImgId").attr("src",ctx+"/kaptcha?r=" +Math.random( ));
}